package zhongbo.javaweb.instagram.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 说明：
 *
 * @author zhongboWork
 * @version 1.0
 * @since 2021-12-30 19:26
 */
@Slf4j
public class HttpUtil {


    public static Map<String, String> cookieToMap(String cookieSource) {
        Map<String, String> cookieMap;
        String[] cookies = cookieSource.split(";");
        cookieMap = new HashMap<>(cookies.length);
        for (String cookie : cookies) {
            String[] cookieValue = cookie.split("=");
            String key = cookieValue[0];
            String value = cookieValue[1];
            cookieMap.put(key, value.trim());
        }
        return cookieMap;
    }

    public static String mapToCookie(Map<String, String> cookieMap) {
        StringBuilder sb = new StringBuilder();
        for (String key : cookieMap.keySet()) {
            sb.append(key).append("; ").append(cookieMap.get(key));
        }
        return sb.toString();
    }

    public static String updateMid(String cookies) throws IOException {
        String mid = EntityUtils.toString(HttpClientUtil.chooseInsClient().execute(new HttpGet("https://www.instagram.com/web/__mid/")).getEntity());
        if (StringUtils.isEmpty(mid)) {
            log.warn("获取 mid 失败!");
        } else {
            log.info("获取到 mid: {}", mid);
        }
        Map<String, String> cookieToMap = cookieToMap(cookies);
        cookieToMap.put("mid", mid);
        return mapToCookie(cookieToMap);
    }
}
